<script setup lang="ts">
import {Chart, OmitedEChartsOption} from "@vue-chart/echart"

const props = defineProps({
  dataSource: {
    type: Array<any>,
    default: () => []
  }
})

const maxAmount = ref<Number>(0)
const range = ref<Array<Number>>([])
const chartOptions = ref<OmitedEChartsOption>({
  xAxis: {
    type: 'category',
    data: ['0~100元']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      data: [0,],
      type: 'bar'
    }
  ]
});
const getAmount = () => {
  // 计算最大值
  props.dataSource.map(item => {
    if (maxAmount.value < parseInt(item.real_wap_price)) {
      maxAmount.value = parseInt(item.real_wap_price)
    }
  })
}
const showChart = ref(false)
onMounted(() => {
  getAmount()
})
watch(() => props.dataSource, () => {
  getAmount()
}, {deep: true})
const staticData = ref<Array<any>>([]);
watch(() => range.value, () => {
  showChart.value = false;
  let label = []
  let data = []
  staticData.value = [];
  for (let i = 0; i < range.value.length; i++) {
    if (i > 0) {
      let name = `${range.value[i - 1]}~${range.value[i]}元`;
      let number = props.dataSource.filter(item => parseInt(item.real_wap_price) > range.value[i - 1] && parseInt(item.real_wap_price) <= range.value[i]).length;
      label.push(name)
      data.push(number)
      staticData.value.push({
        name: name,
        number: number,
        proportion: `${(number / props.dataSource.length * 100).toFixed(2)}%`
      })
    }
  }
  chartOptions.value = {
    tooltip: {
      trigger: 'item',
    },
    xAxis: {
      type: 'category',
      data: label
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: '商品数量',
        data: data,
        barWidth: '50',
        type: 'bar'
      }
    ]
  }
  nextTick(() => {
    showChart.value = true;
  })
}, {deep: true})
</script>

<template>
  <a-row type="flex">
    <a-col flex="1">
      <Chart style="height: 320px;margin-top: -10px;" :options="chartOptions" v-if="showChart"/>
    </a-col>
    <a-col flex="1" style="width: 50%;">
      <base-table table-name="相似宝贝-价格分布" size="small" v-if="showChart" :columns="[
          {
            title:'价格带',
            dataIndex:'name',
            sorter: (a, b) => a.name.length - b.name.length,
          },
          {
            title:'商品数量',
            dataIndex:'number',
            align:'center',
            sorter: (a, b) => a.number - b.number,
          },
          {
            title:'商品数量占比',
            dataIndex:'proportion',
            align:'center',
            width:'120px',
            sorter: (a, b) => parseInt(a.proportion.length) - parseInt(b.proportion.length),
          },
      ]" :data-source="staticData" :scroll="{
        y: 320
      }"/>
    </a-col>
  </a-row>
  <div style="text-align: center;">
    <price-range :max="maxAmount" @change="(r)=>range=r"/>
  </div>
</template>

<style scoped>

</style>
